package com.token.iot.bratterycharging.gateway.sender;

import java.util.Map;

import org.springframework.stereotype.Component;

import com.outstanding.framework.core.Logger;
import com.outstanding.framework.core.PendingException;
import com.outstanding.framework.log.LoggerFactory;
import com.outstanding.framework.utils.Base64;
import com.token.iot.bratterycharging.gateway.AbstractSender;
import com.token.iot.bratterycharging.gateway.ChannelHandlerContextManager;
import com.token.iot.bratterycharging.gateway.IDGeneration;
import com.token.iot.bratterycharging.gateway.ResCode;
import com.token.iot.bratterycharging.gateway.Semaphore;
import com.token.iot.bratterycharging.gateway.SemaphoreManager;
import com.token.iot.bratterycharging.gateway.Sender;
import com.token.iot.bratterycharging.gateway.utils.ByteUtil;

import io.netty.channel.ChannelHandlerContext;

/**
 * 请求设备类型
 * 
 * @author chenzhixuan
 *
 */
@Component("ASYSender")
public class ASYSender extends AbstractSender {

	private static ChannelHandlerContextManager manager = new ChannelHandlerContextManager();

	private static Logger loger = LoggerFactory.getLogger(ASYSender.class);

	@Override
	public Object send(String imei, Map<String, String> params) throws PendingException {
		// 查找对应的HandlerContext
		ChannelHandlerContext context = manager.getChannelHandlerContextByImei(imei);
		String sessionid ="000000";
		String command = code + sessionid + "/";
		byte[] c = ByteUtil.addFlag(command.getBytes());
		context.writeAndFlush(c);
		String key = imei + "@" + sessionid;
		// 信号量
		Semaphore semaphore = SemaphoreManager.registerCommand(key, this);
		try {
			semaphore.await();
		} catch (InterruptedException e) {
			loger.error(e);
			throw new PendingException(ResCode.semaphoreTimeOut);
		}
		// 得到回复
		String response = semaphore.getResponse();
		loger.info("The device Type =" + response);
		String deviceType = response.substring(13);
		return deviceType;
	}

}
